//
//  PTWebSheetView.swift
//  Donpo
//
//  Created by benwang on 2020/1/15.
//  Copyright © 2020 benco. All rights reserved.
//

import UIKit
import WebKit
import SnapKit

extension PTSheetHandle {
    /// 单按钮网页弹框
    func sheet(title: String? = nil,
               url: URL,
               ensure: String,
               handle: Handle? = nil) {

         sheet(title: nil, url: url, buttons: (nil, ensure), handle: handle)
     }

    /// 双按钮网页弹框
    func sheet(title: String? = nil,
               url: URL,
               buttons: (cancel: String?, ensure: String),
               handle: Handle? = nil) {

        let sheet = PTWebSheetView()
        sheet.title = title
        sheet.url = url
        sheet.buttons = buttons

        self.sheet(PTSheetHandle.Content(sheet: sheet), handle: handle)
    }
}

/// 可配置的弹框协议
extension PTWebSheetView: PTSheetConfigurable {
    var handle: PTSheetHandle.Handle? {
        get {
            return completeHandle
        }
        set {
            completeHandle = newValue
        }
    }

    func shouldUpdateLayoutConstraints() {

        self.snp.remakeConstraints { (make) in
            make.top.equalToSuperview().offset(50).priority(.high)
            make.left.equalToSuperview().offset(50).priority(.high)
            make.right.equalToSuperview().offset(-50).priority(.high)
            make.bottom.equalToSuperview().offset(-50).priority(.high)
            make.width.lessThanOrEqualTo(430)
            make.height.lessThanOrEqualTo(600)
            make.center.equalToSuperview()
        }
    }
}

class PTWebSheetView: UIView {

    private let titleLabel: UILabel = {
        let label = UILabel(frame: .zero)
        label.textAlignment = .center
        label.font = UIFont.boldSystemFont(ofSize: 18)
        return label
    }()

    private lazy var webView: WKWebView = {
        let view = WKWebView(frame: .zero)
        view.navigationDelegate = self
        return view
    }()

    private var line: UIView = {
        let view = UIView(frame: .zero)
        view.backgroundColor = .groupTableViewBackground
        return view
    }()

    private let agreementButton: UIButton = {
        let button = UIButton(type: .system)
        button.layer.cornerRadius = 20
        button.layer.masksToBounds = true
        button.backgroundColor = .systemOrange
        button.setTitle("同意", for: .normal)
        button.setTitleColor(.white, for: .normal)
        button.addTarget(self, action: #selector(agreementClicked), for: .touchUpInside)
        return button
    }()

    private let disagreementButton: UIButton = {
        let button = UIButton(type: .system)
        button.setTitle("不同意", for: .normal)
        button.setTitleColor(.black, for: .normal)
        button.addTarget(self, action: #selector(disagreementClicked), for: .touchUpInside)
        return button
    }()

    private var webTopConstraint: Constraint?
    private var agreementBottomConstraint: Constraint?
    private var agreementHeightConstraint: Constraint?
    private var lineHeightConstraint: Constraint?

    private var completeHandle: PTSheetHandle.Handle?

    var title: String? {
        didSet {
            self.titleLabel.text = title ?? ""
            if title != nil {
                self.webTopConstraint?.update(offset: 50)
            } else {
                self.webTopConstraint?.update(offset: 10)
            }
        }
    }

    var url: URL! {
        didSet {
            webView.load(URLRequest(url: url))
        }
    }

    var buttons: (cancel: String?, ensure: String)! {
        didSet {
            if let text = buttons.cancel {
                disagreementButton.setTitle(text, for: .normal)
                agreementBottomConstraint?.update(offset: -50)
            } else {
                lineHeightConstraint?.update(offset: 1)
                agreementBottomConstraint?.update(offset: -5)
                agreementHeightConstraint?.update(offset: 50)
                agreementButton.backgroundColor = .white
                agreementButton.setTitleColor(.systemOrange, for: .normal)
            }
            agreementButton.setTitle(buttons.ensure, for: .normal)
        }
    }

    override init(frame: CGRect) {
        super.init(frame: frame)
        backgroundColor = .white
        layer.cornerRadius = 8
        layer.masksToBounds = true

        self.addSubview(titleLabel)
        self.addSubview(webView)
        self.addSubview(line)
        self.addSubview(disagreementButton)
        self.addSubview(agreementButton)

        renderContentView()
    }

    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    func renderContentView() {

        titleLabel.snp.makeConstraints { (make) in
            make.left.right.equalToSuperview()
            make.top.equalToSuperview().offset(10)
            make.height.equalTo(40)
        }

        webView.snp.makeConstraints { (make) in
            self.webTopConstraint = make.top.equalToSuperview().constraint
            make.left.right.equalTo(agreementButton)
            make.bottom.equalTo(line.snp.top).offset(-20)
        }

        line.snp.makeConstraints { (make) in
            make.top.equalTo(webView.snp.bottom)
            make.left.right.equalToSuperview()
            make.bottom.equalTo(agreementButton.snp.top)
            self.lineHeightConstraint = make.height.equalTo(0).constraint
        }

        agreementButton.snp.makeConstraints { (make) in
            make.left.equalToSuperview().offset(15)
            make.right.equalToSuperview().offset(-15)
            self.agreementHeightConstraint = make.height.equalTo(40).constraint
            self.agreementBottomConstraint = make.bottom.equalToSuperview().offset(-5).constraint
        }

        disagreementButton.snp.makeConstraints { (make) in
            make.left.equalToSuperview().offset(15)
            make.right.equalToSuperview().offset(-15)
            make.height.equalTo(40)
            make.bottom.equalToSuperview().offset(-5)
        }
    }

    @objc func agreementClicked() {
        completeHandle?(.ensure)
    }

    @objc func disagreementClicked() {
        completeHandle?(.cancel)
    }
}

extension PTWebSheetView: WKNavigationDelegate {

    func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
        guard let url = navigationAction.request.url else {
            decisionHandler(.cancel)
            return
        }

        if navigationAction.navigationType == .linkActivated {
            if #available(iOS 10.0, *) {
                UIApplication.shared.open(url, options: [:], completionHandler: nil)
            } else {
                UIApplication.shared.openURL(url)
            }
            decisionHandler(.cancel)
        } else {
            decisionHandler(.allow)
        }
    }
}
